package pdftools;

import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.xobject.PdfImageXObject;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

public class ExtractByItext {

    public static void main(String[] args) throws IOException {
        String filePath = "E:\\DOWNLOAD\\cmp_make_jpg_mask.pdf";
        PdfReader pdfReader = new PdfReader(filePath);
        PdfDocument document = new PdfDocument(pdfReader);
        PdfObject object;
        PdfStream stream;
        int numberOfPages = document.getNumberOfPages();
        System.out.println(numberOfPages);
        for (int i = 1; i < numberOfPages; i++) {
            PdfPage page = document.getPage(i);
            PdfResources resources = page.getResources();
            Iterator<PdfName> iterator = resources.getResourceNames().iterator();
          while (iterator.hasNext()){
              PdfName pdfName = iterator.next();
              System.out.println(pdfName);
              if(PdfName.Image.equals(pdfName)){
                  PdfImageXObject image = resources.getImage(pdfName);
                  BufferedImage bi = image.getBufferedImage();

                  File file = new File("E:\\DOWNLOAD\\images\\"+ System.currentTimeMillis());
                  Thumbnails.of(bi).scale(1f).outputQuality(0.25f).outputFormat("jpg").toFile(file);
              }
          }
        }

       /* for (PdfIndirectReference indRef : document.listIndirectReferences()) {
            object = indRef.getRefersTo();
            if (object == null || !object.isStream()) {
                continue;
            }
            stream = (PdfStream) object;

            PdfName asName = stream.getAsName(PdfName.Subtype);
            PdfName filter = stream.getAsName(PdfName.Filter);
            System.out.println(asName+":"+filter);
            if (!PdfName.Image.equals(asName)) {
                continue;
            }
            if (!PdfName.DCTDecode.equals(stream.getAsName(PdfName.Filter))) {
                continue;
            }
            PdfImageXObject image = new PdfImageXObject(stream);
            BufferedImage bi = image.getBufferedImage();

            File file = new File("E:\\DOWNLOAD\\images\\"+ new Date().getTime());
            Thumbnails.of(bi).scale(1f).outputQuality(0.5f).outputFormat("jpg").toFile(file);
        }*/
    }
}
